//
//  UIView+Ext.m
//  Ymc
//
//  Created by 寇广超 on 2022/11/22.
//  Copyright © 2022 YMC. All rights reserved.
//

#import "UIView+Ext.h"
#import <objc/message.h>
@interface UIView ()
@property (nonatomic,copy)void(^clickedAction)(id);
@end
@implementation UIView (Ext)
- (void)setClickedAction:(void (^)(id))clickedAction{
    objc_setAssociatedObject(self, @"AddClickedEvent", clickedAction, OBJC_ASSOCIATION_COPY_NONATOMIC);
}

- (void (^)(id))clickedAction{
    return objc_getAssociatedObject(self, @"AddClickedEvent");
}
- (void)addClickedBlock:(void(^)(id obj))clickedAction{
     self.clickedAction = clickedAction;
    // hy:先判断当前是否有交互事件，如果没有的话。。。所有gesture的交互事件都会被添加进gestureRecognizers中
     if (![self gestureRecognizers]) {
         self.userInteractionEnabled = YES;
         // hy:添加单击事件
         UITapGestureRecognizer *tap = [[UITapGestureRecognizer alloc] initWithTarget:self action:@selector(tap)];
         [self addGestureRecognizer:tap];
    }
}
-(void)removeGesture{
    NSMutableArray *newges = [NSMutableArray arrayWithArray:self.gestureRecognizers];
       for (int i =0; i<[newges count]; i++) {
           [self removeGestureRecognizer:[newges objectAtIndex:i]];
       }
}
- (void)tap{
    if (self.clickedAction) {
        self.clickedAction(self);
    }
}

- (REBaseViewController *)baseViewController {
    for (UIView* next = [self superview]; next; next = next.superview) {
        UIResponder* nextResponder = [next nextResponder];
        if ([nextResponder isKindOfClass:[REBaseViewController class]]) {
            return (REBaseViewController *)nextResponder;
        }
    }
    return nil;
}
+(instancetype)viewFromXIB{
    
    NSString *name=NSStringFromClass(self);
    
    UIView *xibView=[[[NSBundle mainBundle] loadNibNamed:name owner:nil options:nil] firstObject];
    
    if(xibView==nil){
        NSLog(@"CoreXibView：从xib创建视图失败，当前类是：%@",name);
    }
    
    return xibView;
}
@end
